package com.njlime.cms.controller.sys;

import com.njlime.cms.entities.MaterialsImage;
import com.njlime.cms.entities.MaterialsImageGroup;
import com.njlime.cms.entities.MaterialsVoice;
import com.njlime.cms.entities.MaterialsVoiceGroup;
import com.njlime.cms.service.sys.MaterialImageGroupService;
import com.njlime.cms.service.sys.MaterialImageService;
import com.njlime.cms.service.sys.MaterialVoiceGroupService;
import com.njlime.cms.service.sys.MaterialVoiceService;
import com.njlime.cms.util.UrlUtil;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.PageBean;
import com.njlime.member.entiies.TMemberGroup;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 素材管理-音频
 * Created by Dean on 2017/8/10.
 */
@Controller
@RequestMapping(value = "/cms/meterial")
public class MaterialVoiceController extends BaseController {

    @Resource
    MaterialVoiceService materialVoiceService;

    @Resource
    MaterialVoiceGroupService materialVoiceGroupService;
    /**
     * 图片素材入口页面
     *
     * @return
     */
    @RequestMapping(value = "/toVoiceList" )
    public ModelAndView roleManage(HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("/sys/content/meterial/voice");
        TMemberGroup info = new TMemberGroup();
       int unitId = UserUtils.getUser().getRootUnit().getId();

        modelAndView.addObject("groupList",materialVoiceGroupService.list(unitId));

        return modelAndView;
    }

    /**
     * 音频新增
     * @param request
     * @param info
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addVoice")
    public String addVoice(HttpServletRequest request,MaterialsVoice info ){
        try {
           int unitId = UserUtils.getUser().getRootUnit().getId();

            info.setUnit_id(unitId);
            info.setDel(0);
            info.setCreate_time(new Date().getTime()/1000 );

            materialVoiceService.save(info);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error(e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 查询音频素材
     *
     * @param request
     * @param groupId 组id
     * @return
     */
    @RequestMapping(value = "getVoiceList", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getImageList(PageBean pageBean, HttpServletRequest request,int groupId,String name ) {
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            return toJsonListData(materialVoiceService.getImageList(pageBean ,unitId,groupId,name));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 删除音频素材
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "delVoice", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String delVoice( String id, HttpServletRequest request ) {
        try {
          int unitId = UserUtils.getUser().getRootUnit().getId();
            materialVoiceService.delImage( id,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 查询音频素材分组
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getVoiceGroupList", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getImageGroupList(PageBean pageBean, HttpServletRequest request ) {
        try {

             int unitId = UserUtils.getUser().getRootUnit().getId();

            Map map = materialVoiceGroupService.getSumMember(unitId);
            List<MaterialsVoiceGroup> list = materialVoiceGroupService.list( unitId);
            Map resMap = new HashMap();

            resMap.put("sumMap",map);
            resMap.put("list",list);

            return toJsonListData(resMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 分组新增
     * @param request
     * @param info
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addVoiceGroup")
    public String addGroup(HttpServletRequest request,MaterialsVoiceGroup info ){
        try {
           int unitId = UserUtils.getUser().getRootUnit().getId();

            info.setUnit_id(unitId);
            info.setCount(0);
            info.setDel(0);
            info.setCreate_time(new Date() );
            materialVoiceGroupService.add(info);
            return toJsonSuccessData();
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 修改图片分组
     * @param ids
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "editVoiceGroup", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String editVoiceGroup(String ids,int groupId, HttpServletRequest request, HttpServletResponse response) {
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            materialVoiceService.editImageGroup(ids,groupId,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error("", e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 修改分组
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "editVoiceGroupName", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String editVoiceGroupName(String id,String name, HttpServletRequest request, HttpServletResponse response) {
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            materialVoiceService.editGroup(id,name,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error("", e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 删除分组
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "deleteVoiceGroup", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String deleteVoiceGroup(String id,  HttpServletRequest request, HttpServletResponse response) {
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            materialVoiceService.deleteGroup(id,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error("", e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    @RequestMapping(value = "downloadVoice")
    @ResponseBody
    public void downloadImage(HttpServletResponse response, String ids){
        try {
            String filename = new String((System.currentTimeMillis() + ".zip").getBytes("UTF-8"), "ISO8859-1");//控制文件名编码
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            String[] idArr = ids.split(",");
            for (int i = 0; i < idArr.length; i++) {
                MaterialsVoice voice = materialVoiceService.findOne(Integer.valueOf(idArr[i]));
                zos.putNextEntry(new ZipEntry("(" + (i+1) + ") " + voice.getTitle() + voice.getVoice_path().substring(voice.getVoice_path().lastIndexOf("."))));
                byte[] bytes = UrlUtil.getImageFromNetByUrl(voice.getVoice_path());
                zos.write(bytes, 0, bytes.length);
                zos.closeEntry();
            }
            zos.close();
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
            OutputStream os = response.getOutputStream();
            os.write(bos.toByteArray());
            os.close();
        } catch (Exception ex) {
            logger.error("Exception", ex);
        }
    }

}
